import React, { Component } from 'react'
import { Button, FlatList, Modal, Text, View } from 'react-native'
import UserShow from './s183/UserShow'
import UserAddor from './s183/UserAddor'
import UserEditor from './s183/UserEditor'
let users=[{id:1,uname:'john',address:"金星"},
{id:2,uname:'tom',address:"土星"}]
export default class App extends Component {
  state={users,visible:false,updateVisible:false,current:{}}
  max=2
  _delete=id=>{
    let users=this.state.users
    let index=users.findIndex(user=>user.id===id)
    users.splice(index,1)
    this.setState({users})
  }
  _renderUser=({item})=><UserShow onSelectCurrent={this._select} onDeleteUser={this._delete} user={item}/>
  
  _select=uid=>{
    let index=this.state.users.findIndex(user=>user.id===uid)
    this.setState({current:this.state.users[index],updateVisible:true})
  }
  _add=()=>this.setState({visible:true})
  _update=user=>{
    let users=this.state.users
    let index=users.findIndex(u=>u.id===user.id)
    users.splice(index,1,user)//更新
    this.setState({users,updateVisible:false})
  }
  _userAdd=user=>{
    let users=this.state.users
    user.id=++this.max
    users.push(user)
    this.setState({users,visible:false})
  }
  render() {
    return (
      <View>
        <Button title="添 加" onPress={this._add}/>
        {/* 添加的Modal */}
        <Modal transparent={true} visible={this.state.visible}>
          <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
              <View style={{backgroundColor:'green',width:300,height:300}}>
              <UserAddor onAddUser={this._userAdd}/></View>
          </View>
        </Modal>
        {/* 更新的Modal */}
        <Modal transparent={true} visible={this.state.updateVisible}>
          <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
              <View style={{backgroundColor:'yellow',width:300,height:300}}>
                <UserEditor onUserUpdate={this._update} user={this.state.current}/>
              </View>
          </View>
        </Modal>
        <FlatList data={this.state.users} renderItem={this._renderUser} 
        keyExtractor={user=>users.id}/>
      </View>
    )
  }
}
